import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver';
/* Default icons are required for TinyMCE 5.3 or above */
import 'tinymce/icons/default';
// Any plugins you want to use has to be imported
import 'tinymce/plugins/lists';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/fullscreen';

import BaseFormWidget from './BaseFormWidget.js';
import {
    getOpt
} from "../tools.js";

var template = require('./templates/TextAreaWidget.mustache');

const setupTinyMce = function (kwargs) {
    /*
     * Setup a tinymce editor
     * kwargs are tinymce init options to be added to the default ones
     *
     * Should at least provide the selector key
     *
     * https://www.tinymce.com/docs/
     */
    // Following block is kept in sync manually with vue_sources/src/components/forms/RichTextArea.vue
    let skin = "oxide";
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
        skin = "oxide-dark";
    }
    let options = {
        body_class: 'form-control',
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        width: "100%",
        //height: "auto",
        language: "fr_FR",
        skin_url: "/fanstatic/fanstatic/js/build/tinymce-assets/skins/ui/" + skin,
        language_url: "/fanstatic/fanstatic/js/build/tinymce-assets/langs/fr_FR.js",
        content_css: "/fanstatic/fanstatic/js/build/tinymce-assets/skins/ui/" + skin + "/content.css",
        plugins: "lists advlist searchreplace visualblocks fullscreen paste",
        theme_advanced_resizing: true,
        theme: "silver",
        skin: skin,
        strict_loading_mode: true,
        mode: "none",
        convert_fonts_to_spans: true,
        paste_as_text: true,
        toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
            'bullist numlist outdent indent | link image | print preview media fullpage | ' +
            'forecolor backcolor emoticons',
        menubar: 'edit view insert format tools table',
        browser_spellcheck: true
    };

    _.extend(options, kwargs);
    tinymce.init(options);
}

const TextAreaWidget = BaseFormWidget.extend({
    /*
     * A textarea widget
     *
     * Support following options :
     *
     *   :param str title:
     *   :param str description:
     *   :param str field_name:
     *   :param str value:
     *   :param int rows:
     *   :param bool editable:
     *   :param str placeholder:
     *   :param bool tinymce: Richtext widget ?
     *
     * Triggers two type of events
     *
     *   change : on KeyUp
     *   finish : when leaving the field
     */
    tagName: 'div',
    className: 'form-group',
    template: template,
    ui: {
        textarea: 'textarea'
    },
    events: {
        'keyup @ui.textarea': 'onKeyUp',
        'blur @ui.textarea': 'onBlur'
    },
    onKeyUp: function () {
        this.triggerChange(this.getUI('textarea').val());
    },
    onBlur: function () {
        this.triggerFinish(this.getUI('textarea').val());
    },

    templateContext: function () {
        let ctx = this.getCommonContext();
        let more_ctx = {
            value: getOpt(this, 'value', ''),
            rows: getOpt(this, 'rows', 2),
        }

        return Object.assign(ctx, more_ctx);
    },
    onAttach: function () {
        var tiny = getOpt(this, 'tinymce', false);
        if (tiny) {
            var onblur = this.onBlur.bind(this);
            var onkeyup = this.onKeyUp.bind(this);
            setupTinyMce({
                selector: "#" + this.getTagId(),
                init_instance_callback: function (editor) {
                    editor.on('blur', onblur);
                    editor.on('keyup', onkeyup);
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                }
            });
        }
    }
});
export default TextAreaWidget;
